package com.neusoft.freshmenapp.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.neusoft.freshmenapp.R;
import com.neusoft.freshmenapp.adapter.ClassmateAdapter;
import com.neusoft.freshmenapp.domain.Student;
import com.neusoft.freshmenapp.util.Httputil;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ClassmateListActivity extends AppCompatActivity {

    private List<Student> classmateList = new ArrayList<>();
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classmate_list);

        listView = findViewById(R.id.lv_classmate);
        String uri = "http://10.0.2.2:8080/freshmenapp/classmate/listbyclassname";
        initStudents(uri);

    }

    private void initStudents(String uri) {

        //通过okhttp工具类，发送登录请求

        JSONObject json = new JSONObject();
        try {
            json.put("className", "17移动1班");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        Httputil.request(uri, json, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                 final String responseData = response.body().string();
                Log.d("TAG", "onResponse: "+responseData);

                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(responseData);
                            JSONArray jsonArray =  jsonObject.getJSONArray("list");
                            for (int i = 0 ; i < jsonArray.length() ; i++){
                                JSONObject obj = jsonArray.getJSONObject(i);
                                String name =  obj.getString("name");
                                Student student = new Student(name);
                                classmateList.add(student);
                            }

                            ClassmateAdapter adapter = new ClassmateAdapter(ClassmateListActivity.this,R.layout.classmate_list,classmateList);
                            listView.setAdapter(adapter);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });

    }
}
